import { noop } from 'lodash'
import { useBoolean } from 'ahooks'

import { useToast } from './useToast'

export type UseLoadingifyOptions = {
  showLoading?: boolean
  showToast?: boolean
}

export function useLoadingify<R = any, P extends unknown[] = unknown[]>(
  service: Service<R, P>,
  options: UseLoadingifyOptions = {}
) {
  const toast = useToast()
  const [loading, { setTrue, setFalse }] = useBoolean(false)

  const handle = async (...args: P) => {
    setTrue()

    let hide = noop
    const { showLoading = true, showToast } = options

    if (showLoading) {
      hide = toast.loading()
    }

    try {
      return await service(...args)
    } catch (e) {
      if (showToast) {
        toast.error((e as Error).message || '操作失败')
      }

      throw e
    } finally {
      hide()

      setFalse()
    }
  }

  return [loading, handle] as const
}
